<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;

class SessionsController extends Controller{

	public function __construct(){
		$this->middleware('guest', [
			'only' => ['create'],
		]);
	}

	/**
	 * 用户注册页面
	 *
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function create(){
		return view("session.create");
	}

	/**
	 * 用户登录
	 *
	 * @param Request $request
	 * @return \Illuminate\Http\RedirectResponse|void
	 * @throws \Illuminate\Validation\ValidationException
	 */
	public function store(Request $request){
		$credentials = $this->validate($request, [
			'email'    => "required|email|max:255",
			'password' => "required",
		]);
		if(Auth::attempt($credentials, $request->has('remember'))){
			if(Auth::user()->activated){
				session()->flash('success', '登陆成功');
				$fallback = route('users.show', Auth::user());
				return redirect()->intended($fallback);
			}else{
				Auth::logout();
				session()->flash('warning','您的账号还未激活,请检查邮箱中的注册邮箱进行激活');
				return redirect('/');
			}

		}else{
			session()->flash('danger', '很抱歉，您的邮箱和密码不匹配');
			return redirect()->back()->withInput();
		}
	}

	/**
	 * 用户退出
	 */
	public function destroy(){
		Auth::logout();
		session()->flash('success', '退出成功');
		return redirect('login');
	}
}
